﻿using mBook.Data;
using mBook.DataManager;
using mBook.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using mBook.Views;
using NotificationsExtensions.ToastContent;
using Windows.UI.Notifications;
using mBook.Utils;
using mBook.Models;
using Windows.ApplicationModel.Search;
using System.Collections.ObjectModel;

// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231

namespace mBook
{
    /// <summary>
    /// A page that displays a grouped collection of items.
    /// </summary>
    public sealed partial class GroupedItemsPage : mBook.Common.LayoutAwarePage
    {
        private SearchPane searchPane;

        public GroupedItemsPage()
        {
            this.InitializeComponent();
            //searchPane = SearchPane.GetForCurrentView();
        }

        //List<DataEbook> listDownloading = new List<DataEbook>();

        //public List<DataEbook> ListDownloading
        //{
        //    get { return listDownloading; }
        //    set { listDownloading = value; }
        //}

        #region download 
        public async void AddItemDownload(EbookViewModel ebook)
        {
            ManagerDataViewModel.GetAllDownloadingEbooks().Add(ebook);

            updateInfoDownload();
            // don't have item downloading 
            if (ManagerDataViewModel.GetAllDownloadingEbooks().Count == 1)
            {
                try
                {
                    bool isSuccess = await DataService.GetInstance().Download(ebook.EBook);

                    downloadFinish(ebook, isSuccess);
                }
                catch (Exception e)
                {
                    //DataViewModel.getAllDownloadingEbooks().Remove(ebook);
                    //showToast(e.Message);
                    downloadFinish(ebook, false);
                    App.ShowMessage(e.Message);
                }

            }
            
            
        }

        async void downloadFinish(EbookViewModel ebook, bool isSuccess)
        {
            ManagerDataViewModel.GetAllDownloadingEbooks().Remove(ebook);

            if (isSuccess)
            {
                ManagerDataViewModel.AddMyEbook(ebook);
                showToast(Constants.DOWNLOAD_SUCCESSFUL);
            }
            updateInfoDownload();

            if (ManagerDataViewModel.GetAllDownloadingEbooks().Count > 0)
            {

                EbookViewModel newEbook = ManagerDataViewModel.GetAllDownloadingEbooks().ElementAt(0);

                try
                {
                    bool isSuccess2 = await DataService.GetInstance().Download(newEbook.EBook);
                    downloadFinish(newEbook, isSuccess2);
                }
                catch (Exception e)
                {
                    //DataViewModel.getAllDownloadingEbooks().Remove(newEbook);
                    //showToast(e.Message);
                    downloadFinish(newEbook, false);
                }
            }
        }

        void updateInfoDownload()
        {
            String text = "";
            if (ManagerDataViewModel.GetAllDownloadingEbooks().Count > 0)
            {
               
                if (ManagerDataViewModel.GetAllDownloadingEbooks().Count > 1)
                {
                    text = "Downloading " + ManagerDataViewModel.GetAllDownloadingEbooks().Count + " ebooks...";
                }
                else
                {
                    text = "Downloading 1 ebook...";
                }

            }
            else
            {
                text = "";
            }

            ManagerDataViewModel.SetStatus(text);
     
        }

        

        #endregion

        void showToast(String text)
        {
            IToastNotificationContent toastContent = null;
            IToastText01 templateContent = ToastContentFactory.CreateToastText01();
            templateContent.TextBodyWrap.Text = text;
            toastContent = templateContent;

            //NotifyUser(toastContent.GetContent(), NotifyType.StatusMessage);

            // Create a toast, then create a ToastNotifier object to show
            // the toast
            ToastNotification toast = toastContent.CreateNotification();

            // If you have other applications in your package, you can specify the AppId of
            // the app to create a ToastNotifier for that application
            ToastNotificationManager.CreateToastNotifier().Show(toast);
        }

        private void OnSearchPaneSuggestionsRequested(SearchPane sender, SearchPaneSuggestionsRequestedEventArgs e)
        {
            var queryText = e.QueryText;
            var request = e.Request;
            foreach (CategoryviewModel category in ManagerDataViewModel.getAllGroups())
            {
                if (category.Title.ToLower().Contains(queryText.ToLower()))
                {
                    // Add suggestion to Search Pane
                    request.SearchSuggestionCollection.AppendQuerySuggestion(category.Title);

                    // Break since the Search Pane can show at most 5 suggestions
                    if (request.SearchSuggestionCollection.Size >= Constants.SearchPaneMaxSuggestions)
                    {
                        break;
                    }
                }
            }
        }

        

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            ObservableCollection<CategoryviewModel> myEbook = null;
            try
            {
                prgBar.Visibility = Windows.UI.Xaml.Visibility.Visible;

                myEbook = await ManagerDataViewModel.getMyEbook();
                var sampleDataGroups = await ManagerDataViewModel.GetAllData();
                this.DefaultViewModel["Groups"] = sampleDataGroups;                

                statusDownloading.DataContext = ManagerDataViewModel.GetStatusDownload();

                prgBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                semanticZoom.Visibility = Windows.UI.Xaml.Visibility.Visible;               
            }
            catch (Exception e)
            {
                this.DefaultViewModel["Groups"] = myEbook;

                prgBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                App.ShowMessage(e.Message);
            }
        }


        //protected override void OnNavigatedFrom(NavigationEventArgs e)
        //{
        //    searchPane.SuggestionsRequested -= new TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>(OnSearchPaneSuggestionsRequested);
        //}

        #region event

        /// <summary>
        /// Invoked when a group header is clicked.
        /// </summary>
        /// <param name="sender">The Button used as a group header for the selected group.</param>
        /// <param name="e">Event data that describes how the click was initiated.</param>
        void Header_Click(object sender, RoutedEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            Dictionary<String, object> dict = new Dictionary<String, object>();
            dict["GroupID"] = ((CategoryviewModel)group).UniqueId;
            dict["MainPage"] = this;
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(GroupDetailPage), dict);
        }

        /// <summary>
        /// Invoked when an item within a group is clicked.
        /// </summary>
        /// <param name="sender">The GridView (or ListView when the application is snapped)
        /// displaying the item clicked.</param>
        /// <param name="e">Event data that describes the item clicked.</param>
        void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            var itemId = ((EbookViewModel)e.ClickedItem).UniqueId;
            Dictionary<String, object> dict = new Dictionary<String, object>();
            dict["itemID"] = itemId;
            dict["MainPage"] = this;
            //This ebook already download --> go to ebook viewer
            if (itemId.Contains(Constants.PREFIX_MY_EBOOK_ID))
            {
                
                this.Frame.Navigate(typeof(EpubViewerPage), dict);
            }else
            {
                
                this.Frame.Navigate(typeof(ItemDetailPage), dict);
            }
            
        }

        

        private async void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            ObservableCollection<CategoryviewModel> myEbooks = null;
            try
            {
                prgBar.Visibility = Windows.UI.Xaml.Visibility.Visible;
                btnRefresh.IsEnabled = false;

                myEbooks = await ManagerDataViewModel.getMyEbook();
                var sampleDataGroups = await ManagerDataViewModel.ResetData();
                this.DefaultViewModel["Groups"] = sampleDataGroups;


                prgBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnRefresh.IsEnabled = true;
            }
            catch (Exception ex)
            {
                this.DefaultViewModel["Groups"] = myEbooks;
                btnRefresh.IsEnabled = true;
                prgBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                App.ShowMessage(ex.Message);
                
            }
        }

        private void GridView_headerClick(object sender, ItemClickEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(GroupDetailPage), ((CategoryviewModel)group).UniqueId);
        }


        private void downloading_click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(DownloadingPage), this);
        }

        private void GridView_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            // Determine what group the Button instance represents
            var group = (sender as FrameworkElement).DataContext;

            // Navigate to the appropriate destination page, configuring the new page
            // by passing required information as a navigation parameter
            this.Frame.Navigate(typeof(GroupDetailPage), ((CategoryviewModel)group).UniqueId);
        }

        #endregion

    }

    public enum NotifyType
    {
        StatusMessage,
        ErrorMessage
    };
}
